package cn.snmp.mutual.util;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import cn.snmp.mutual.adapter.AbstractMibNodeAdapter;
import cn.snmp.mutual.filter.AbstractFilter;
import cn.snmp.mutual.nms.SnmpString;
import cn.snmp.mutual.nms.SnmpVar;
import cn.snmp.mutual.nms.SnmpVarBind;
import cn.snmp.mutual.nms.mibs.MibProfileLoader;
import lombok.extern.slf4j.Slf4j;
import cn.snmp.mutual.data.ObjService;

/**
 * @author dengkn
 * */
@Slf4j
public class OperatorUtilities {
	

	
	public static LinkedList<String> shortInstance(ObjService osInstance) {
		LinkedList vInstances = new LinkedList();
		LinkedList varray = new LinkedList();
		ObjService osReverse = new ObjService();

		try {
			for (Object key : osInstance.getStoreValueMap().keySet()) {
				Long arg10 = Long.valueOf(osInstance.getStringValue((String) key));
				if (!osReverse.getStringValue(arg10.toString()).equals("")) {
					throw new Exception("");
				}
				varray.add(arg10);
				osReverse.setValue(arg10.toString(), key);
			}
	
			Object[] arg7 = varray.toArray();
			Arrays.sort(arg7);

			for (int arg9 = 0; arg9 < arg7.length; ++arg9) {
				vInstances.add(osReverse.getStringValue(arg7[arg9].toString()));
			}

			return vInstances;
		} catch (Exception arg6) {
			log.debug("--> short instance unsuccessful, result object order may not right.");
			for (Object key : osInstance.getStoreValueMap().keySet()) {
				vInstances.add(key);
			}
			return vInstances;
		}
	}

	public static void changeLogic(ObjService result) {
		if (result.objectSize("RowSet") > 0) {
			LinkedList rowSets = result.getContainedObjSet("RowSet");
			result.remove("RowSet");
			for (int i = 0; i < rowSets.size(); ++i) {
				ObjService snmpRowSet = (ObjService) rowSets.get(i);
				ObjService corbaRowSet = new ObjService("RowSet");
				if (result.getStringValue("Type").equalsIgnoreCase("Table")) {
					corbaRowSet.setValue("Instance", snmpRowSet.getStringValue("Instance"));
				}
				for (int j = 0; j < result.objectSize("MibNode"); ++j) {
					ObjService mibNodeInfo = result.objectAt("MibNode", j);
					String corbaName = mibNodeInfo.getStringValue("Node");
					String logicName = mibNodeInfo.getStringValue("Logic");
					HashMap snmpHashMap = snmpRowSet.getCurrentHashMap();
					HashMap corbaHashMap = corbaRowSet.getCurrentHashMap();
					Object value = snmpHashMap.get(logicName);
					corbaHashMap.put(corbaName, value);
				}
				result.addContainedObject(corbaRowSet);
			}
		}

	}

	public static boolean isFinish(String[] nodeBaseOIDs, SnmpVarBind[] leafNodeBinds) {
		if (nodeBaseOIDs == null && leafNodeBinds == null) {
			return true;
		} else {
			boolean flag = true;

			for (int i = 0; i < nodeBaseOIDs.length; ++i) {
				String strBaseOID = nodeBaseOIDs[i];
				String strFullOID = leafNodeBinds[i].getObjectID().toString();
				if (strFullOID.length() > strBaseOID.length()
						&& strFullOID.substring(0, strBaseOID.length() + 1).equals(strBaseOID + ".")) {
					flag = false;
					break;
				}
			}
			return flag;
		}
	}

	public static boolean isFinish(String[] nodeBaseOIDs, SnmpVarBind[] leafNodeBinds, String[] previousNodeOIDss) {
		if (previousNodeOIDss == null) {
			return isFinish(nodeBaseOIDs, leafNodeBinds);
		} else if (nodeBaseOIDs == null && leafNodeBinds == null) {
			return true;
		} else {
			boolean flag = true;

			int i;
			String strFullOID;
			for (i = 0; i < nodeBaseOIDs.length; ++i) {
				strFullOID = nodeBaseOIDs[i];
				String strFullOID1 = leafNodeBinds[i].getObjectID().toString();
				if (strFullOID1.length() > strFullOID.length()
						&& strFullOID1.substring(0, strFullOID.length() + 1).equals(strFullOID + ".")) {
					flag = false;
					break;
				}
			}

			for (i = 0; i < nodeBaseOIDs.length; ++i) {
				strFullOID = leafNodeBinds[i].getObjectID().toString();
				if (strFullOID.equalsIgnoreCase(previousNodeOIDss[i])) {
					flag = true;
					break;
				}
			}
			return flag;
		}
	}

	public static String getInstance(String[] nodeBaseOIDs, SnmpVarBind[] leafNodeBinds) {
		if (nodeBaseOIDs == null && leafNodeBinds == null) {
			return "";
		} else {
			for (int i = 0; i < nodeBaseOIDs.length; ++i) {
				String strBaseOID = nodeBaseOIDs[i];
				String strFullOID = leafNodeBinds[i].getObjectID().toString();
				if (strFullOID.length() >= strBaseOID.length()
						&& strFullOID.substring(0, strBaseOID.length() + 1).equals(strBaseOID + ".")) {
					String instance = strFullOID.substring(strBaseOID.length() + 1);
					return instance;
				}
			}
			return "";
		}
	}

	public static ObjService getTableRow(ObjService result, LinkedList indexNodeLinkedList, LinkedList accessNodeLinkedList,
										 HashMap bindTable, ObjService mibNodeNameTable, String[] nodeOIDList, SnmpVarBind[] rowValueList,
										 AbstractFilter filter, ObjService option) {
		if (rowValueList == null) {
			result.setValue("ErrCode", "2");
			result.setValue("ErrDesc", "Table is null");
			return result;
		} else {
			String FilterNode = result.getStringValue("FilterNode");
			String FilterValue = result.getStringValue("FilterValue");
			String instance;
			String e;
			if (!FilterNode.equals("")) {
				instance = mibNodeNameTable.getStringValue(FilterNode);
				if (!instance.equals("")) {
					Integer j = (Integer) bindTable.get(instance);
					e = rowValueList[j.intValue()].getVariable().toString();
					if (e.equalsIgnoreCase(FilterValue)) {
						DumpUtil.debug("Logic [" + FilterNode + "], Value [" + e + "], filter it ...");
						result.setValue("ErrCode", "0");
						result.setValue("ErrDesc", "Get Table Success");
						return result;
					}
				}
			}
			ObjService rowSet = new ObjService("RowSet");
			instance = null;
			String logicName;
			int arg20;
			for (arg20 = 0; arg20 < nodeOIDList.length; ++arg20) {
				e = nodeOIDList[arg20];
				logicName = rowValueList[arg20].getObjectID().toString();
				if (logicName.length() >= e.length() && logicName.substring(0, e.length() + 1).equals(e + ".")) {
					instance = logicName.substring(e.length() + 1);
					rowSet.setValue("Instance", instance);
					break;
				}
			}

			if (instance == null) {
				result.setValue("ErrCode", "2");
				result.setValue("ErrDesc", "Table row is null");
				return result;
			} else {
				calculateTableIndexsValue(indexNodeLinkedList, instance, rowSet, option);

				for (arg20 = 0; arg20 < accessNodeLinkedList.size(); ++arg20) {
					try {
						ObjService arg21 = (ObjService) accessNodeLinkedList.get(arg20);
						logicName = arg21.getStringValue("Logic");
						String nodeOID = mibNodeNameTable.getStringValue(logicName);
						Integer pos = (Integer) bindTable.get(nodeOID);
						SnmpVar value = rowValueList[pos.intValue()].getVariable();
						HashMap table = rowSet.getCurrentHashMap();
						table.put(logicName, readSnmpVar(value, arg21, option, rowSet));
					} catch (Exception arg19) {
						result.setValue("ErrCode", "1006");
						result.setValue("ErrDesc", arg19.toString());
						return result;
					}
				}

				if (filter != null) {
					filter.reset();
				}

				if (filter != null && filter.isFilter(result, rowSet)) {
					DumpUtil.debug("one table row is filtered...");
				} else {
					result.addContainedObject(rowSet);
				}

				result.setValue("ErrCode", "0");
				result.setValue("ErrDesc", "Get Table Success");
				return result;
			}
		}
	}

	public static void calculateTableIndexsValue(LinkedList indexNodes, String instance, ObjService rowSet,
			ObjService option) {
		ObjService nodeOIDTable = new ObjService();
		ObjService nativeValue = new ObjService("Native Value");
		LinkedList calcuIndexs = new LinkedList();

		String node;
		String access;
		for (int subInstance = 0; subInstance < indexNodes.size(); ++subInstance) {
			ObjService HashMap = (ObjService) indexNodes.get(subInstance);
			String i = HashMap.getStringValue("OID");
			node = HashMap.getStringValue("Logic");
			access = nodeOIDTable.getStringValue(i);
			if (access.equalsIgnoreCase("")) {
				nodeOIDTable.setValue(i, node);
				calcuIndexs.add(HashMap);
			}
		}

		String arg21 = "." + instance;

		String logic;
		String oid;
		String adapterClass;
		for (int arg22 = 0; arg22 < calcuIndexs.size(); ++arg22) {
			ObjService arg24 = (ObjService) calcuIndexs.get(arg22);
			node = arg24.getStringValue("Logic");
			access = arg24.getStringValue("Access");
			logic = arg24.getStringValue("TypeString");
			oid = arg24.getStringValue("SyntaxName");
			String[] strValue = Utilities.stringSplit(arg21, '.');
			adapterClass = "";
			BigInteger e = new BigInteger(strValue[1]);
			BigInteger Value = new BigInteger(strValue.length - 2 + "");
			if (arg22 == calcuIndexs.size() - 1 && e.compareTo(Value) != 0) {
				adapterClass = arg21.substring(1, arg21.length());
				arg21 = "";
			} else {
				ObjService subValueList = getIndexValue(arg21, arg24);
				if (subValueList.getStringValue("ErrCode").equals("0")) {
					adapterClass = subValueList.getStringValue("IndexValue");
					arg21 = subValueList.getStringValue("SubInstance");
				}
			}

			if (access.equalsIgnoreCase("NOACCESS")) {
				int i1;
				String[] arg30;
				if (oid.equalsIgnoreCase("MacAddress")) {
					arg30 = Utilities.stringSplit(adapterClass, '.');
					adapterClass = "";

					for (i1 = 0; i1 < arg30.length; ++i1) {
						String subMacAddress = "00" + Integer.toHexString(Integer.parseInt(arg30[i1]));
						subMacAddress = subMacAddress.substring(subMacAddress.length() - 2);
						if (i1 != arg30.length - 1) {
							adapterClass = adapterClass + subMacAddress + ":";
						} else {
							adapterClass = adapterClass + subMacAddress;
						}
					}
				} else if (logic.equalsIgnoreCase("STRING") || logic.equalsIgnoreCase("OBJID")) {
					arg30 = Utilities.stringSplit(adapterClass, '.');
					if (arg30.length == 1 && arg30[0].compareTo("33") < 0 && arg30[0].compareTo("126") > 0) {
						adapterClass = arg30[0];
					} else {
						adapterClass = "";

						for (i1 = 0; i1 < arg30.length; ++i1) {
							if (!arg30[i1].equals("")) {
								adapterClass = adapterClass + (char) Integer.parseInt(arg30[i1]);
							}
						}
					}
				}
				nativeValue.setValue(node, adapterClass);
			}
		}

		HashMap arg23 = rowSet.getCurrentHashMap();

		for (int arg25 = 0; arg25 < indexNodes.size(); ++arg25) {
			ObjService arg26 = (ObjService) indexNodes.get(arg25);
			access = arg26.getStringValue("Access");
			if (access.equalsIgnoreCase("noaccess")) {
				logic = arg26.getStringValue("Logic");
				oid = arg26.getStringValue("OID");
				String arg27 = nativeValue.getStringValue(nodeOIDTable.getStringValue(oid));
				adapterClass = arg26.getStringValue("MibNodeAdapter");
				if (adapterClass.equals("") && arg26.objectSize("MibNodeAdapter") > 0) {
					adapterClass = arg26.objectAt("MibNodeAdapter", 0).getStringValue("MibNodeAdapter");
				}

				if (adapterClass.equals("")) {
					rowSet.setValue(logic, arg27);
				} else {
					try {
						SnmpString arg28 = new SnmpString(arg27);
						Object arg29 = readSnmpVar(arg28, arg26, option, rowSet);
						arg23.put(logic, arg29);
					} catch (Exception arg20) {
						arg23.put(logic, arg20.toString());
					}
				}
			}
		}
		if (!arg21.equals("")) {
			DumpUtil.debug("Calculate table index error, index node value may be not right...");
		}

	}

	public static ObjService getTableRowSets(ObjService tableInfo, ObjService result, SnmpVarBind[][] rowValueList) {
		if (rowValueList == null) {
			result.setValue("ErrCode", "2");
			result.setValue("ErrDesc", "Table is null");
			return result;
		} else {
			AbstractFilter rowFilter = AbstractFilter.getFilter(result);
			if (rowFilter != null) {
				rowFilter.init(tableInfo);
			}

			int mibNodeCount = result.objectSize("MibNode");
			LinkedList indexNodeLinkedList = new LinkedList();
			LinkedList accessNodeLinkedList = new LinkedList();
			ObjService mibNodeNameTable;
			for (int mibNodeOIDTable = 0; mibNodeOIDTable < mibNodeCount; ++mibNodeOIDTable) {
				mibNodeNameTable = result.objectAt("MibNode", mibNodeOIDTable);
				String nodeOIDLinkedList = mibNodeNameTable.getStringValue("OID");
				if (!nodeOIDLinkedList.equals("")) {
					String nodeOIDs = mibNodeNameTable.getStringValue("Access");
					if (!nodeOIDs.equalsIgnoreCase("NOACCESS")) {
						accessNodeLinkedList.add(mibNodeNameTable);
					}

					if (Utilities.isIndexNode(mibNodeNameTable)) {
						indexNodeLinkedList.add(mibNodeNameTable);
					}
				}
			}
			ObjService arg26 = new ObjService();
			mibNodeNameTable = new ObjService();
			LinkedList arg27 = new LinkedList();

			String FilterNode;
			String FilterValue;
			for (int arg28 = 0; arg28 < accessNodeLinkedList.size(); ++arg28) {
				ObjService bindTable = (ObjService) accessNodeLinkedList.get(arg28);
				FilterNode = bindTable.getStringValue("OID");
				FilterValue = bindTable.getStringValue("Logic");
				mibNodeNameTable.setValue(FilterValue, FilterNode);
				String row = arg26.getStringValue(FilterNode);
				if (!row.equalsIgnoreCase("true")) {
					arg26.setValue(FilterNode, "true");
					arg27.add(FilterNode);
				}
			}

			String[] arg29 = new String[arg27.size()];

			for (int arg30 = 0; arg30 < arg27.size(); ++arg30) {
				arg29[arg30] = (String) arg27.get(arg30);
			}

			HashMap arg31 = new HashMap();

			for (int arg32 = 0; arg32 < arg29.length; ++arg32) {
				arg31.put(arg29[arg32], new Integer(arg32));
			}

			FilterNode = result.getStringValue("FilterNode");
			FilterValue = result.getStringValue("FilterValue");

			for (int arg33 = 0; arg33 < rowValueList.length; ++arg33) {
				String instance;
				String e;
				if (!FilterNode.equals("")) {
					instance = mibNodeNameTable.getStringValue(FilterNode);
					if (!instance.equals("")) {
						Integer j = (Integer) arg31.get(instance);
						e = rowValueList[arg33][j.intValue()].getVariable().toString();
						if (e.equalsIgnoreCase(FilterValue)) {
							DumpUtil.debug("Logic [" + FilterNode + "], Value [" + e + "], filter it ...");
							continue;
						}
					}
				}

				ObjService rowSet = new ObjService("RowSet");
				instance = null;

				String logicName;
				int arg34;
				for (arg34 = 0; arg34 < arg29.length; ++arg34) {
					e = arg29[arg34];
					logicName = rowValueList[arg33][arg34].getObjectID().toString();
					if (logicName.length() > e.length() && logicName.substring(0, e.length() + 1).equals(e + ".")) {
						instance = logicName.substring(e.length() + 1);
						rowSet.setValue("Instance", instance);
						break;
					}
				}

				if (instance == null) {
					break;
				}

				calculateTableIndexsValue(indexNodeLinkedList, instance, rowSet, tableInfo);

				for (arg34 = 0; arg34 < accessNodeLinkedList.size(); ++arg34) {
					try {
						ObjService arg35 = (ObjService) accessNodeLinkedList.get(arg34);
						logicName = arg35.getStringValue("Logic");
						String nodeOID = mibNodeNameTable.getStringValue(logicName);
						Integer pos = (Integer) arg31.get(nodeOID);
						SnmpVarBind bind = rowValueList[arg33][pos.intValue()];
						String oid = bind.getObjectID().toString();
						if (oid.startsWith(nodeOID + ".")) {
							SnmpVar value = bind.getVariable();
							HashMap table = rowSet.getCurrentHashMap();
							table.put(logicName, readSnmpVar(value, arg35, tableInfo, rowSet));
						}
					} catch (Exception arg25) {
						log.error("getTableRowSets error "+arg25);
						result.setValue("ErrCode", "1006");
						result.setValue("ErrDesc", arg25.toString());
						return result;
					}
				}

				if (rowFilter != null) {
					rowFilter.reset();
				}

				if (rowFilter != null && rowFilter.isFilter(result, rowSet)) {
					DumpUtil.debug("filter one table row ...");
				} else {
					result.addContainedObject(rowSet);
				}
			}

			result.setValue("ErrCode", "0");
			result.setValue("ErrDesc", "Get Table Success");
			return result;
		}
	}

	public static ObjService getIndexValue(String instance, ObjService mibNode) {
		String syntaxName = mibNode.getStringValue("SyntaxName");
		String label = mibNode.getStringValue("Label");
		String syntax = mibNode.getStringValue("Syntax");
		String typeString = mibNode.getStringValue("TypeString");
		ObjService result = new ObjService("Result");

		try {
			String[] e = Utilities.stringSplit(instance, '.');
			boolean indexDotCount = false;
			String indexValue = null;
			String SubInstance = null;
			if (syntaxName.equalsIgnoreCase("MacAddress")) {
				indexDotCount = true;
				indexValue = e[1] + "." + e[2] + "." + e[3] + "." + e[4] + "." + e[5] + "." + e[6];
				if (1 + indexValue.length() + 1 < instance.length()) {
					SubInstance = instance.substring(1 + indexValue.length(), instance.length());
				} else {
					SubInstance = "";
				}

				result.setValue("SubInstance", SubInstance);
				result.setValue("IndexValue", indexValue);
				result.setValue("ErrCode", "0");
				return result;
			} else {
				if (!typeString.equalsIgnoreCase("STRING") && !typeString.equalsIgnoreCase("OBJID")) {
					if (typeString.equalsIgnoreCase("BITSTRING")) {
						DumpUtil.debug("Cannot calculate index value, TypeString is ]BITSTRING].");
					} else if (typeString.equalsIgnoreCase("IPADDRESS")) {
						indexDotCount = true;
						indexValue = e[1] + "." + e[2] + "." + e[3] + "." + e[4];
						if (1 + indexValue.length() + 1 < instance.length()) {
							SubInstance = instance.substring(1 + indexValue.length(), instance.length());
						} else {
							SubInstance = "";
						}
					} else {
						indexDotCount = true;
						indexValue = e[1];
						if (1 + indexValue.length() + 1 < instance.length()) {
							SubInstance = instance.substring(1 + indexValue.length(), instance.length());
						} else {
							SubInstance = "";
						}
					}
				} else {
					int arg14 = Integer.parseInt(e[1]);
					int start;
					if (arg14 != 0) {
						start = 0;

						int end;
						for (end = 0; end < arg14; ++end) {
							start += 1 + e[1 + end + 1].length();
						}

						end = 1 + e[1].length() + 1;
						int end1 = end + start - 1;
						indexValue = instance.substring(end, end1);
						if (1 + e[1].length() + start < instance.length()) {
							SubInstance = instance.substring(1 + e[1].length() + indexValue.length() + 1,
									instance.length());
						} else {
							SubInstance = "";
						}
					} else {
						indexValue = "";
						start = 1 + e[1].length();
						if (1 + e[1].length() < instance.length()) {
							SubInstance = instance.substring(1 + e[1].length(), instance.length());
						} else {
							SubInstance = "";
						}
					}
				}

				result.setValue("SubInstance", SubInstance);
				result.setValue("IndexValue", indexValue);
				result.setValue("ErrCode", "0");
				return result;
			}
		} catch (Exception arg13) {
			DumpUtil.debug(arg13);
			result.setValue("ErrCode", "1");
			return result;
		}
	}

	public static ObjService findMibNode(ObjService mibTable, String nodeLogicName) {
		if (mibTable == null) {
			return null;
		} else {
			for (int i = 0; i < mibTable.rowSize("MibNode"); ++i) {
				ObjService mibNode = mibTable.objectAt("MibNode", i);
				String logic = mibNode.getStringValue("Logic");
				if (logic.equals(nodeLogicName)) {
					return mibNode;
				}
			}

			return null;
		}
	}

	public static Object readSnmpVar(SnmpVar var, ObjService mibnode, ObjService option, ObjService rowSet) {
		AbstractMibNodeAdapter adapter = AbstractMibNodeAdapter.getMibNodeAdapter(mibnode, option);
		adapter.setRowSet(rowSet);
		Object value = adapter.nativeReadMibData(var, mibnode);
		if (value == null) {
			value = new String(adapter.getClass().toString() + ".nativeReadMibData() return null...");
		}

		return value;
	}

	public static SnmpVar writeSnmpVar(Object value, ObjService mibnode, ObjService option, ObjService rowSet) {
		AbstractMibNodeAdapter adapter = AbstractMibNodeAdapter.getMibNodeAdapter(mibnode, option);
		adapter.setRowSet(rowSet);
		return adapter.nativeWriteMibData(value, mibnode);
	}

	public static void setTempletVersion(ObjService result) {
		result.setValue("TempletVersion", "1.1.1");
	}

	public static boolean isRmpAlter(String mibProfile) {
		boolean isAlter = false;
		String baseMibProfile = null;
		if (mibProfile != null && !mibProfile.equalsIgnoreCase("")) {
			baseMibProfile = mibProfile.substring(0, mibProfile.lastIndexOf(".rmp"));
		}

		MibProfileLoader mibProfileLoader = new MibProfileLoader(baseMibProfile + "/");
		if (mibProfileLoader.getURL(baseMibProfile + "/") != null) {
			isAlter = true;
		} else {
			isAlter = false;
		}

		return isAlter;
	}
}